/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ig.export.loader;

import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import ig.export.to.ParametroTO;
import ig.export.to.TipoJrxmlTO;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 *
 * @author usuario
 */
public class JRXMLLoader extends AbstractLoader {

    public static final String JASPERREPORT = "jasperReport";

    public static final String QUERYSTRING = "queryString";

    public JRXMLLoader(File archivo) throws FileNotFoundException, SAXException, IOException {
        super(null);
        InputStream xmlStream = null;
        try {
            DOMParser domParser = new DOMParser();

            // Parses the DOM Tree
            xmlStream = new FileInputStream(archivo);
            domParser.parse(new InputSource(xmlStream));

            // Gets the root node
            Document doc = domParser.getDocument();
            NodeList list = doc.getElementsByTagName(JASPERREPORT);
            if (list.getLength() > 0) {
                node = list.item(0);
            }
        } finally {
            try {
                xmlStream.close();
            } catch (Exception e) {
            }
        }
    }

    @Override
    public Object loadStructure() throws Exception {
        TipoJrxmlTO tipoJrxmlTO = new TipoJrxmlTO();
        Node queryStringNode = getChild(QUERYSTRING);
        List<Node> cDataList = getChildrenCDATA(queryStringNode);
        if (!cDataList.isEmpty()) {
            tipoJrxmlTO.setSQL(cDataList.get(0).getNodeValue().trim());
        }
        List<ParametroTO> listPatametros = (List<ParametroTO>) new ParametrosLoader(node).loadStructure();
        for (ParametroTO parametroTO : listPatametros) {
            if ( tipoJrxmlTO.getSQL().contains("$P{"+parametroTO.getNombre()+"}")){
                tipoJrxmlTO.getParametroTOs().add(parametroTO);
            }
        }
        //tipoJrxmlTO.setParametroTOs((List<ParametroTO>) new ParametrosLoader(node).loadStructure());
        return tipoJrxmlTO;
    }
}
